<?php
/**
 * @Author: Ron Chen
 * @Date:   2016-12-18 14:59:49
 * @Last Modified by:   Ron Chen
 * @Last Modified time: 2017-02-20 22:18:38
 */

namespace backend\controllers;

use Yii;
use yii\helpers\FileHelper;  
use yii\helpers\Html;  
use yii\helpers\Url;  
use yii\imagine\Image;  
use yii\web\Controller;  
use yii\web\UploadedFile;  

use common\helpers\StringHelper;
use common\models\sys\Attachment;

class UploadController extends Controller  {
	
	public $enableCsrfValidation = false;//禁用Csrf验证  

	const UPLOAD_IMAGE_MAX_SIZE = '10 * 1024 * 1024'; // 10M

	 /** 
     * 上传图片到临时目录 
     * @params $filekey    // 文件 Key
     * @params $fileobject // 存储路径
     * @params $extend     // 扩展参数
     * @return string 
     * @throws \yii\base\Exception 
     */
	public function actionImage(){
		$res = [];
		if (Yii::$app->request->isPost) {
			$initialPreview = [];
            $initialPreviewConfig = [];

            $filekey    = Yii::$app->request->post('filekey');
            $fileObject = Yii::$app->request->post('fileObject');
            $objectId   = Yii::$app->request->post('objectId');
            $objectType = Yii::$app->request->post('objectType');

            $images = UploadedFile::getInstancesByName($filekey);

            if (count($images) > 0) {
            	foreach ($images as $key => $image) {
            		if ($image->size > 10 * 1024 * 1024) {
                        $res = ['error' => sprintf('当前图片大小%s，图片最大不可超过10M',$image->size)];
                        return json_encode($res);
                    }
                    if (!in_array(strtolower($image->extension), array('gif', 'jpg', 'jpeg', 'png'))) {  
                        $res = ['error' => '请上传标准图片文件, 支持gif,jpg,png和jpeg.'];  
                        return json_encode($res);  
                    }

                    $filedir  = sprintf('./uploads/%s',$fileObject);
                    $pickey   = StringHelper::genuuid();
                    $filename = sprintf("%s.%s",$pickey,$image->getExtension());
                    
                    // 如果不存在则创建目录
                    if (!file_exists($filedir)) {
                        FileHelper::createDirectory($filedir, 777);  
                    }
                    
                    $file     = sprintf("%s%s",$filedir,$filename);
                    if ($image->saveAs($file)) {
                        // 处理显示结果

                        $dir = sprintf('/uploads/%s%s',$fileObject,$filename);
                    	$imgpath = Url::to("@web".$dir, true);
                        // 插入数据库
                        $this->handleAttachment($filename,$dir,["id"=>$objectId,"type"=>$objectType]);
                    	array_push($initialPreview, $imgpath);
                        // 删除图片的配置 url + 配置参数 extra
                    	$config = [  
                            'caption' => $filename,  
                            'width'   => '120px',  
                            'url'     => '/upload/delete-image',
                            'key'     => $pickey,  
                            'extra'   => [
                                'filename' => $filename,
                                'object_id'=> $objectId,
                                'type'     => $objectType,
                            ]  
                        ];
                        array_push($initialPreviewConfig, $config);
                        $res = [  
                            "initialPreview"       => $initialPreview,  
                            "initialPreviewConfig" => $initialPreviewConfig,  
                            "imgfile" => "<input name='ImageFilesPath[]' id='" . $pickey . "' type='hidden' value='" . $imgpath . "'/>"  
                        ];
                    }
            	}
            }

            return json_encode($res);
		}

		$res = ['error' => '错误的请求方式'];
		return json_encode($res);
	}

    /**
     * 处理文件路径
     */
    private function handleAttachment($filename,$filepath,$extend=[]){
        $data = [
            "filename" => $filename,
            "fileurl"  => $filepath,
            "object_id"=> isset($extend["id"]) ? $extend["id"] : 0,
            "type"     => isset($extend["type"]) ? $extend["type"] : 0,
        ];

        $attachment = new Attachment();
        if($attachment->insertAttachment($data)){
            return true;
        }

        return false;
    }


	/** 
     * 删除上传到临时目录的图片 
     * @return string 
     */  
    public function actionDeleteImage()
    {  
        $error = '';  
        if (Yii::$app->request->isPost) {
            $filename = yii::$app->request->post("filename");
            $objectId = yii::$app->request->post("object_id");  
            $type     = yii::$app->request->post("type");

            $delCondition  = sprintf(" object_id=%d AND type=%d AND filename=%s ",$objectId,$type,$filename);
            $delAttachment = Attachment::find()->where($delCondition)->orderBy('id desc')->limit(1)->one();
            if ($delAttachment) {
                $delAttachment->isvalid = Attachment::CARD_ATTACH_NOT_VALID;
                $delAttachment->save();
            }

        }  
        return json_encode($error);  
    }
}